﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.OleDb;
using System.IO;
using System.Reflection;
using System.Runtime.InteropServices;
using Public;
using DevComponents.DotNetBar.Controls;
using DevComponents.DotNetBar;
using Entity;

namespace Check_Barcode
{
    public partial class Input_Excel : DevComponents.DotNetBar.Office2007Form
    {
        public Input_Excel()
        {
            InitializeComponent();
        }
        private string[] cols2 = new string[] {  "条码", "最大对比次数","备注" };
        private string[] names2 = new string[] { "条码", "最大对比次数","备注" };
        private Microsoft.Office.Interop.Excel.Application rptExcel = null;
        protected object missing = Missing.Value;
        string dbstr = "";
        string _NO = "";
        protected DataTable dt = new DataTable();
        DBAccessOperater db1;
        Class1 Class1 = new Class1();
        private void Input_Excel_Load(object sender, EventArgs e)
        {
             dbstr = "Provider=Microsoft.Jet.OleDb.4.0;Data Source=" + Application.StartupPath + @"\\DB\Location.mdb";//Access数据库相对路径;);
             db1 = new DBAccessOperater(dbstr);
            //initDataView(this.dataGridViewX2, cols2, names2);
            string[,] cell = new string[,] {  { "BILL_NO", "单据编号" },
            {"QTY","条码数量"},{"checked_QTY","已对比条码数量"},{"STATUS","审核状态"},{ "OPERATOR", "操作员工号" },
            {"CREATE_BY","创建人"}, {"CREATE_DATE","创建时间"},{"UPDATE_BY","更新人"},
            {"UPDATE_DATE","更新时间"},{"AUDIT_BY","审核人"},{"AUDIT_DATE","审核时间"},{"REMARK","备注"}};//
            initDataView2(dataGridViewX1, cell);//装载表头列标题

            //添加勾选列
            dataGridViewX1.Columns.Insert(0, _DataGridViewColumn("check", "选择"));
            dataGridViewX1.Columns["check"].Visible = true;
            dataGridViewX1.Columns["check"].Frozen = true;//冻结列
            dataGridViewX1.Columns["check"].ReadOnly = false;
            string[,] cell3 = new string[,] { { "BILL_NO", "单据编号" }, { "SN", "条码" }, { "Check_QTY", "最大对比次数" }, { "Checked_QTY", "已对比次数" }, { "REMARK", "备注" } };
            initDataView2(dataGridViewX3, cell3);//装载表头列标题
            initDataView2(dataGridViewX2, cell3);//装载表头列标题
            comboBox_add(dataGridViewX1, comboBoxEx2);//将dataGridView的列标题字段添加到下拉框
            comboBox_add(comboBoxEx3);//装载条件
            comboBoxEx2.SelectedIndex = 2;
            comboBoxEx3.SelectedIndex = 0;
            superTabControl1.SelectedTabIndex = 0;//初始时显示第一页签

            string[] cols1 = { "ID", "样板条码", "扫描条码", "作业时间", "校验状态", "批次号" };
            string[] names1 = { "ID", "mac1", "mac2", "Operation_time", "iCheck_sta", "BILL_NO" };
            initDataView(dataGridViewX4, cols1, names1);

            dateX_CREATE_DATE.Value = DateTime.Now.AddDays(-5).Date;
            dateX_CREATE_DATE2.Value = DateTime.Now.AddDays(+1).Date;
            _填充信息("", false);
        }

        private void buttonX3_Click(object sender, EventArgs e)
        {
            Import2();
        }


        #region 初始化表格
        public void initDataView(DataGridView dataView, string[] cols, string[] names)
        {
            dataView.AllowUserToAddRows = false;
            dataView.AllowUserToDeleteRows = false;
            dataView.AllowUserToOrderColumns = false;
            dataView.AllowUserToResizeRows = false;
            for (int i = 0; i < cols.Length; i++)
            {
                DataGridViewColumn _col = new DataGridViewTextBoxColumn();
                _col.Name = cols[i];
                _col.HeaderText = cols[i];
                _col.ReadOnly = true;
                _col.DataPropertyName = names[i];
                dataView.Columns.Add(_col);
            }
            dataView.AutoGenerateColumns = false;  //让它不自己产生多余的列

        }
        #endregion 初始化表格
        /// <summary>
        ///将二维数组 string[,] Fcell里的列标题字段按顺序装载到DataGridView _dv
        /// </summary>
        /// <param name="_dv">类型：DataGridView</param>
        /// <param name="Fcell">类型：string[][]</param>
        public void initDataView2(DataGridView _dv, string[,] Fcell)
        {
            _dv.DataSource = null;
            // _dv.Columns.Clear();不能直接清除所有列，有些列不是后台加载的（比如反选的列）
            _dv.AllowUserToAddRows = false;
            _dv.AllowUserToDeleteRows = false;
            _dv.AllowUserToOrderColumns = true;
            _dv.AllowUserToResizeRows = false;

            for (int i = 0; i < Fcell.GetLength(0); i++)
            {
                //根据数据库的表的列字段进行装载列标题
                if (Fcell[i, 0] != null)
                {
                    DataGridViewColumn _col = new DataGridViewTextBoxColumn();
                    _col.Name = Fcell[i, 0];
                    _col.HeaderText = Fcell[i, 1];
                    _col.ReadOnly = true;
                    _col.DataPropertyName = Fcell[i, 0];

                    _col.SortMode = DataGridViewColumnSortMode.Automatic;
                    _dv.Columns.Add(_col);
                }

            }
            _dv.AutoGenerateColumns = false;  //让它不自己产生多余的列
        }

        /// <summary>
        ///将DataGridView _dv的列标题字段添加到ComboBox _cb下拉框
        /// </summary>
        /// <param name="_dv">类型DataGridView</param>
        /// <param name="_cb">类型ComboBox</param>
        public void comboBox_add(DataGridView _dv, ComboBox _cb)
        {
            _cb.Items.Clear();
            _cb.Items.Add("");
            foreach (DataGridViewColumn item in _dv.Columns)
            {
                _cb.Items.Add(item.HeaderText);
            }
        }
        public void comboBox_add(ComboBox _cb)
        {
            _cb.Items.Clear();
            //_cb.Items.Add("");
            _cb.Items.Add("包含");
            _cb.Items.Add("等于");

            _cb.Items.Add("前包含");
            _cb.Items.Add("后包含");
            _cb.Items.Add("大于");
            _cb.Items.Add("小于");
            _cb.Items.Add("大于等于");
            _cb.Items.Add("小于等于");
            _cb.Items.Add("不等于");
            _cb.Items.Add("不包含");
            _cb.Items.Add("为空");
            _cb.Items.Add("不为空");

        }
        /// <summary>
        /// 遍历查所传入的数据列的列标题，如果标题名等于所传入的字符str则返回对应列的Name属性
        /// </summary>
        /// <param name="str">类型:string;说明：要查找的列标题字符</param>
        /// <param name="dgvc">类型:DataGridViewColumnCollection;说明：要遍历查找的数据列集合</param>
        /// <returns></returns>
        public string _ziduan(string str, DataGridViewColumnCollection dgvc)
        {
            string str2 = "";
            foreach (DataGridViewColumn item in dgvc)
            {
                if (item.HeaderText.Trim() == str)
                {
                    str2 = item.Name;
                    break;
                }
            }
            return str2;

        }
        /// <summary>
        /// 返回CheckBoxColumn
        /// </summary>
        /// <param name="_name">列名</param>
        /// <param name="_text">列标题显示名称</param>
        /// <returns></returns>
        public static DataGridViewCheckBoxColumn _DataGridViewColumn(string _name, string _text)
        {
            DataGridViewCheckBoxColumn _cl = new DataGridViewCheckBoxColumn();
            _cl.Name = _name;

            // _cl.HeaderCell = new DatagridViewCheckBoxHeaderCell();
            // _cl.HeaderCell.Style =Da
            _cl.HeaderText = _text;
            _cl.FalseValue = 0;
            _cl.IndeterminateValue = 0;
            _cl.TrueValue = 1;
            _cl.Width = 50;
            _cl.Frozen = false;
            //this.checkBox1.UseVisualStyleBackColor = true;
            //this.checkBox1.Visible = false;
            // this.checkBox1.Click += new System.EventHandler(this.checkBox1_Click);
            return _cl;
        }
        /// <summary>
        /// 根据传入的参数查找匹配的逻辑条件并返回
        /// </summary>
        /// <param name="str">类型:string;说明：要查找的逻辑条件匹配字符</param>
        /// <param name="str2">类型:string;说明：夹在逻辑条件里的数据内容</param>
        /// <returns></returns>
        public string _Tiaojian(string str, string str2)
        {
            string str3 = "";
            switch (str)
            {

                case "等于": str3 = " = '" + str2 + "' "; break;
                case "包含": str3 = " like '%" + str2 + "%' "; break;
                case "前包含": str3 = " like '" + str2 + "%' "; break;
                case "后包含": str3 = " like '%" + str2 + "' "; break;
                case "大于": str3 = " > '" + str2 + "' "; break;
                case "小于": str3 = " < '" + str2 + "' "; break;
                case ">=": str3 = " >= '" + str2 + "' "; break;
                case "<=": str3 = " <= '" + str2 + "' "; break;
                case "大于等于": str3 = " >= '" + str2 + "' "; break;
                case "小于等于": str3 = " <= '" + str2 + "' "; break;
                case "<>": str3 = " <> '" + str2 + "' "; break;
                case "不等于": str3 = " <> '" + str2 + "' "; break;
                case "不包含": str3 = " not like '%" + str2 + "%' "; break;
                case "等于空": str3 = " IS NULL "; break;
                case "为空": str3 = " IS NULL "; break;
                case "不等于空": str3 = " IS NOT NULL "; break;
                case "不为空": str3 = " IS NOT NULL "; break;
                case "并且": str3 = " and "; break;
                case "或者": str3 = " or "; break;

            }
            return str3;
        }

        public DataTable ImportExcel(string FilePath, string a)
        {
            //object Nothing = System.Reflection.Missing.Value;

            //创建一个Application对象
            rptExcel = new Microsoft.Office.Interop.Excel.Application();
            rptExcel.Visible = false;
            //app.UserControl = true;
            //app.DisplayAlerts = false;

            Microsoft.Office.Interop.Excel.Workbook workBook1 =
                rptExcel.Workbooks._Open(FilePath, missing, missing, missing, missing, missing,
                missing, missing, missing, missing, missing, missing, missing);
            Microsoft.Office.Interop.Excel.Worksheet sheet1 =
                (Microsoft.Office.Interop.Excel.Worksheet)workBook1.Worksheets.get_Item(1);

            //app.Application.Workbooks.Open(FilePath, Nothing, Nothing, Nothing, Nothing,
            //Nothing, Nothing, Nothing, Nothing, Nothing, Nothing, Nothing, Nothing, Nothing, Nothing);
            //Microsoft.Office.Interop.Excel.Workbooks wbs = app.Workbooks;
            //Microsoft.Office.Interop.Excel.Workbook workbook1 = wbs[1];
            //Microsoft.Office.Interop.Excel.Worksheet sheet1 = (Microsoft.Office.Interop.Excel.Worksheet)workbook1.Worksheets.get_Item(1);//"Sheet2"

            Microsoft.Office.Interop.Excel.Range range1 = null;
            DataTable dt1 = new DataTable();
            FrmProgressBar panelProgress = new FrmProgressBar();
            try
            {

                int rowCount = sheet1.UsedRange.Rows.Count;
                int colCount = sheet1.UsedRange.Columns.Count;
                if (rowCount <= 0)
                    throw new Exception("文件中没有数据记录");
                if (colCount <= 0)
                    throw new Exception("字段个数不对");

                panelProgress.Show();
                float percent;

                for (int i = 0; i < rowCount; i++)
                {//循环行
                    object[] rows = new object[colCount];
                    for (int j = 0; j < colCount; j++)
                    {//循环列
                        range1 = sheet1.get_Range(sheet1.Cells[i + 1, j + 1], sheet1.Cells[i + 1, j + 1]);
                        //object va=range1.MergeCells;
                        //Console.WriteLine("[" + i + "," + j + "]=" + range1.Value2 +"   "+ va.ToString());

                        rows[j] = range1.Value;
                    }
                    if (i == 0)
                    {//单头列
                        for (int j = 0; j < rows.Length; j++)
                        {
                            if (rows[j] == null)
                            {
                                rows[j] = "f" + j;
                            }
                            DataColumn dc = new DataColumn();
                            dc.ColumnName = rows[j].ToString();
                            dt1.Columns.Add(dc);
                        }
                    }
                    else
                    {
                        DataRow dr = dt1.NewRow();
                        for (int j = 0; j < rows.Length; j++)
                        {
                            if (rows[j] == null)
                                rows[j] = "";
                            dr[j] = rows[j];
                        }
                        dt1.Rows.Add(dr);
                    }
                    percent = ((float)(i) * 100) / rowCount;
                    panelProgress._进度条.Text = percent.ToString("n") + "%";
                    panelProgress.progressBar1.Value = Convert.ToInt32(percent);
                    System.Windows.Forms.Application.DoEvents();
                }

            }
            finally
            {
                panelProgress.Close();//隐藏进度条
                rptExcel.Quit();
                KillSpecialExcel();
                Marshal.ReleaseComObject(rptExcel);
                Marshal.ReleaseComObject(sheet1);
                Marshal.ReleaseComObject(workBook1);
                GC.Collect();
            }

            return dt1;
        }
        [DllImport("user32.dll", SetLastError = true)]
        static extern int GetWindowThreadProcessId(IntPtr hWnd, out int lpdwProcessId);
        public void KillSpecialExcel()
        {
            try
            {
                if (rptExcel != null)
                {
                    int lpdwProcessId;
                    GetWindowThreadProcessId(new IntPtr(rptExcel.Hwnd), out lpdwProcessId);
                    System.Diagnostics.Process.GetProcessById(lpdwProcessId).Kill();
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine("Delete Excel Process Error:" + ex.Message);
            }
        }






        #region 开始导入
        bool _导入数据 = false;
        private void btn_import_start_Click(object sender, EventArgs e)
        {
            if (null == dt || dt.Rows.Count <= 0)
            {
                MessageBoxEx.Show("请选择导入的文件");
                return;
            }
         
            DialogResult dr1 = MessageBoxEx.Show("请确认是否导入数据", "确认", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
            if (dr1 != DialogResult.Yes)
            {
                return;
            }
            else
            {
                #region 导数据
                if (!flag)
                {
                    MessageBoxEx.Show("数据有误");
                    return;
                }
                else
                {
                    FrmProgressBar panelProgress = new FrmProgressBar();
                    panelProgress.Show();
                    float percent;
                    int rowCount = dataGridViewX2.Rows.Count;
                    int i = 0;
                    try
                    {
                        foreach (DataGridViewRow r in this.dataGridViewX2.Rows)
                        {
                            input_data_item o = new input_data_item();
                            //MES_EQUID o = new MES_EQUID();
                            o.ID = Guid.NewGuid().ToString();


                            o.BILL_NO = BILL_NO.Text;
                            o.SN = Convert.ToString(r.Cells["条码"].Value);
                            o.Check_QTY = Convert.ToString(r.Cells["最大对比次数"].Value);
                            o.create_by = CREATE_BY.Text;
                            o.create_date = CREATE_DATE.Text;
                            o.update_by = string.Empty;
                            o.update_date = string.Empty;
                            o.REMARK = Convert.ToString(r.Cells["备注"].Value);
                            db1.AddObject(o);

                            percent = ((float)(i++) * 100) / rowCount;
                            panelProgress._进度条.Text = percent.ToString("n") + "%";
                            panelProgress.progressBar1.Value = Convert.ToInt32(percent);
                            System.Windows.Forms.Application.DoEvents();
                        }
                    }
                    catch (Exception ex)
                    {
                        MessageBoxEx.Show(ex.Message);
                        return;
                    }
                    finally
                    {
                        panelProgress.Close();
                    }
                    MessageBoxEx.Show("导入成功");
                    //this.dataGridViewX2.DataSource = null;
                    _导入数据 = true;
                    btn_import_start.Enabled = false;
                    
                }
                #endregion
     

            }
        }
        #endregion

        #region 载入并校验excel
        Boolean flag = true;
        private void Import2()
        {
            flag = true;
            DialogResult dr = openFileDialog1.ShowDialog();
            if (DialogResult.OK != dr)
            {
                return;
            }

            string _FilePath = openFileDialog1.FileName;
            if (_FilePath == "")
            {
                return;
            }

            if (!File.Exists(_FilePath))
            {
                return;
            }
            FilePath.Text = _FilePath;
            dt.Clear();
            DataTable errorTable = new DataTable();

            //dt = ExportReport.INSTANCE().ImportExcel(_FilePath, "");
            //this.dataGridViewX2.DataSource = dt;
            dt = ExcelHelperForNPOI.ExcelToTable(_FilePath);
            this.dataGridViewX2.DataSource = dt;
            FrmProgressBar panelProgress = new FrmProgressBar();
            panelProgress.Show();
            float percent;
            int rowCount = dataGridViewX2.Rows.Count;
            int i = 0;
            try
            {
                //格式判断：
                 //private string[] cols2 = new string[] { "批次代码", "条码", "最大对比次数", "创建人", "创建时间", "备注" };
                foreach (DataGridViewRow r in this.dataGridViewX2.Rows)
                {
                    string _批次代码 = BILL_NO.Text;
                    string _条码 = r.Cells["条码"].Value.ToString();
                    string _最大对比次数 = r.Cells["最大对比次数"].Value.ToString();
                    string _创建人 = CREATE_BY.Text;
                    string _创建时间 = CREATE_DATE.Text;
                    string _备注 = r.Cells["备注"].Value.ToString();

                    #region 条形码检查
                    if (_条码.Trim() == "")
                    {
                        r.Cells["条码"].Style.BackColor = Color.Red;
                        r.Cells["条码"].ToolTipText = "条形码不能为空！";
                        flag = false;
                    }
                    else
                    {
                        if (db1.CheckSQL("select * from input_data_item where SN='" + _条码 + "'"))
                        {
                            r.Cells["条码"].Style.BackColor = Color.Red;
                            r.Cells["条码"].ToolTipText = "该条形码已经存在!";
                            flag = false;
                        }
                        else
                        {
                            foreach (DataGridViewRow row in this.dataGridViewX2.Rows)
                            {
                                if (row.Index >= r.Index)
                                {
                                    break;
                                }
                                else
                                {
                                    if (r.Cells["条码"].Value.ToString() == row.Cells["条码"].Value.ToString())
                                    {
                                        r.Cells["条码"].Style.BackColor = Color.Red;
                                        r.Cells["条码"].ToolTipText = "导入条形码重复出现!";
                                        flag = false;
                                        break;
                                    }
                                }
                            }
                        }
                    }
                    #endregion

                    percent = ((float)(i++) * 100) / rowCount;
                    panelProgress._进度条.Text = percent.ToString("n") + "%";
                    panelProgress.progressBar1.Value = Convert.ToInt32(percent);
                    System.Windows.Forms.Application.DoEvents();
                    QTY.Text = dataGridViewX2.RowCount.ToString();
                }
               
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
            finally
            {
                panelProgress.Close();
            }
            if (flag == false)
            {
                btn_import_start.Enabled = false;
                buttonX_save.Enabled = false;
                MessageBoxEx.Show("发现有问题的数据，请把鼠标移动到红色单元格查看提示！请确认后查询导入");

            }

        }
        #endregion
        private void buttonX_add_Click(object sender, EventArgs e)
        {
            //if (permission.AddFlag != true)
            //{
            //    MessageBox.Show("你没新增权限！");
            //    return;
            //}
            _填充信息("", true);
            _填充从表信息("", false);
            this.pictureBox3.Visible = false;
            string _交易单号 = _GetBillNo("BA", "批次单号");//获取新的单据编号;
            BILL_NO.Text = _交易单号;

            OPERATOR.Text = Class1.user;
            CREATE_BY.Text = Class1.user;

            label_status.Text = "新增";
            CREATE_DATE.Text = DateTime.Now.ToString();
            dataGridViewX2.Columns.Clear(); //清除标题
            dataGridViewX2.DataSource = null;
            initDataView(this.dataGridViewX2, cols2, names2);
        }
        private void _填充信息(string _id, bool _Enabled)
        {
            //_Enabled=true为编辑模式false为详览模式
            buttonX_save.Enabled = _Enabled;//保存
            buttonX_Cancel.Enabled = _Enabled;//取消

            groupPanel4.Visible = _Enabled;

            bool _Enabled2 = _Enabled ? false : true;
            buttonX_delete.Enabled = _Enabled2;//删除
            buttonX_add.Enabled = _Enabled2;//新增
            buttonX_update.Enabled = _Enabled2;//修改
            buttonX_audits.Enabled = _Enabled2;//审核
            //buttonX_Cancel_audits.Enabled = _Enabled2;//反审核
            //buttonX10.Enabled = _Enabled2;

            string sql_ii = "select * from input_data where BILL_NO='" + _id + "'";
            DataTable dt_ii = db1.SelectDataBase(sql_ii);
            if (dt_ii.Rows.Count < 1)
            {
                dt_ii.Rows.Add();
            }

            foreach (DataColumn item in dt_ii.Columns)
            {
                _填充匹配文本框(groupPanel3, dt_ii.Rows[0], item.ColumnName, _Enabled);
            }
            string sql = "select * from input_data where BILL_NO='" + BILL_NO.Text + "' and STATUS='1' ";
            if (db1.CheckSQL(sql))
            {
                this.pictureBox3.Visible = true;
            }
        }

        #region 填充匹配文本框
        public void _填充匹配文本框(Control _Control, DataRow dt_r, string _ColumnName, bool _Enabled)
        {
            foreach (Control c in _Control.Controls)
            {

                if (c.Controls.Count > 0)
                {
                    _填充匹配文本框(c, dt_r, _ColumnName, _Enabled);
                }
                else
                {
                    if (c.Name == _ColumnName)
                    {
                        if (c.Tag + "" == "可编辑")
                        {
                            c.Enabled = _Enabled;
                        }
                        else
                        {//对于非编辑字段，不管在详览状态还是编辑状态都统统设置为不可点击
                            c.Enabled = false;
                        }

                        string c_TypeName = c.GetType().Name;
                        if (c_TypeName.StartsWith("TextBox") || c_TypeName.StartsWith("Label"))//前包含
                        {
                            c.Text = dt_r[_ColumnName] + "";
                        }
                        else if (c_TypeName.StartsWith("DataWindow"))//前包含
                        {
                            c.Text = dt_r[_ColumnName] + "";
                        }
                        else if (c_TypeName.StartsWith("ComboBox"))
                        {
                            c.Text = dt_r[_ColumnName] + "";
                            //if ((c as ComboBox).DataSource != null)
                            //{
                            //    (c as ComboBox).SelectedValue = dt_r[_ColumnName] + "";
                            //}
                            //else
                            //{
                            //    (c as ComboBox).SelectedItem = dt_r[_ColumnName] + "";
                            //}

                        }
                        else if (c_TypeName.StartsWith("ComboBoxEx"))//董涛添加2017-4-4
                        {
                            c.Text = dt_r[_ColumnName] + "";
                        }
                        else if (c_TypeName.StartsWith("CheckBoxX"))
                        {
                            if (dt_r[_ColumnName] + "" == "0" || dt_r[_ColumnName] + "" == "")
                            {
                                (c as CheckBoxX).Checked = false;
                            }
                            else if (dt_r[_ColumnName] + "" == "1")
                            {
                                (c as CheckBoxX).Checked = true;
                            }
                            else
                            {
                                MessageBox.Show("字段:" + c.Name + "赋值失败! 无法给类型为" + c_TypeName + "的控件赋值：" + dt_r[_ColumnName]);
                            }
                        }
                        else if (c_TypeName.StartsWith("CheckBoxX"))
                        {
                            if (dt_r[_ColumnName] + "" == "0" || dt_r[_ColumnName] + "" == "")
                            {
                                (c as CheckBoxX).Checked = false;
                            }
                            else if (dt_r[_ColumnName] + "" == "1")
                            {
                                (c as CheckBoxX).Checked = true;
                            }
                            else
                            {
                                MessageBox.Show("字段:" + c.Name + "赋值失败! 无法给类型为" + c_TypeName + "的控件赋值：" + dt_r[_ColumnName]);
                            }
                        }
                        else if (c_TypeName.StartsWith("SwitchButton"))
                        {
                            if (dt_r[_ColumnName] + "" == "0" || dt_r[_ColumnName] + "" == "")
                            {
                                (c as SwitchButton).Value = false;
                            }
                            else if (dt_r[_ColumnName] + "" == "1")
                            {
                                (c as SwitchButton).Value = true;
                            }
                            else
                            {
                                MessageBox.Show("字段:" + c.Name + "赋值失败!无法给类型为" + c_TypeName + "的控件赋值：" + dt_r[_ColumnName]);
                            }

                        }
                        else if (c_TypeName.StartsWith("DateTimePicker"))
                        {
                            if (dt_r[_ColumnName] + "" == "")
                            {
                                (c as DateTimePicker).Text = "";
                            }
                            else
                            {
                                (c as DateTimePicker).Value = Convert.ToDateTime(dt_r[_ColumnName]);
                            }
                            // (c as DateTimePicker).Value = dt_r[_ColumnName]==null?Convert.ToDateTime(dt_r[_ColumnName]):null;

                        }
                        else if (c_TypeName.StartsWith("DateTimeInput"))
                        {
                            if (dt_r[_ColumnName] + "" == "")
                            {
                                (c as DevComponents.Editors.DateTimeAdv.DateTimeInput).Text = "";
                            }
                            else
                            {
                                (c as DevComponents.Editors.DateTimeAdv.DateTimeInput).Value = Convert.ToDateTime(dt_r[_ColumnName]);
                            }
                            // (c as DateTimePicker).Value = dt_r[_ColumnName]==null?Convert.ToDateTime(dt_r[_ColumnName]):null;

                        }
                        else if (c_TypeName.StartsWith("IntegerInput"))
                        {
                            (c as DevComponents.Editors.IntegerInput).Value = Convert.ToInt32(dt_r[_ColumnName]);
                        }
                        else if (c_TypeName.StartsWith("DoubleInput"))
                        {
                            (c as DevComponents.Editors.DoubleInput).Value = Convert.ToDouble(dt_r[_ColumnName]);
                        }
                        else
                        {
                            MessageBox.Show(_ColumnName + "赋值失败！当前封装的方法函数不支持：" + c_TypeName + " 控件！");
                        }
                        break;

                    }
                }

            }
        }

        #endregion
        #region 获取单号
        public string _GetBillNo(string _单据前缀, string _单据类型)
        {
            string _单号 = string.Empty;
            int _申请单序号 = 1;
            int _序号 = 1;
            string _申请单号 = string.Empty;
            string _单号前缀 = _单据前缀 + DateTime.Now.ToString("yyMMdd");
            string _StrSql = "select  max(billno) from SYS_BILLNO where billno like '" + _单号前缀 + "%' and type='" + _单据类型 + "'   ";//order by CreateTime desc
            string _最后一张单据 = Convert.ToString(db1.GetColumnObject(_StrSql));

            if (string.IsNullOrEmpty(_最后一张单据))
            {
                _申请单号 = _单号前缀 + "001";
            }
            else
            {
                _申请单序号 = Convert.ToInt32(_最后一张单据.ToString().Substring(_单号前缀.Length)) + _序号;
            }
            _单号 = _单号前缀 + _申请单序号.ToString().PadLeft(3, '0');

            string sql = "insert into SYS_BILLNO (BILLNO,TYPE,CreateTime) values('" + _单号 + "','" + _单据类型 + "','" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + "')";
            try
            {

                db1.ExcuteSQL(sql);
            }
            catch (Exception)
            {

                _申请单序号 += 1;
                _单号 = _单号前缀 + _申请单序号.ToString().PadLeft(3, '0');
                string sql1 = "insert into SYS_BILLNO (billno,TYPE,CreateTime) values('" + _单号 + "','" + _单据类型 + "','" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + "')";
                db1.ExcuteSQL(sql1);
                return _单号;
            }
            return _单号;
        }
        #endregion 获取单号
        #region _获取文本框值
        public void _获取文本框值(Control _Control, DataRow dt_r, string _ColumnName)
        {

            foreach (Control c in _Control.Controls)
            {

                if (c.Controls.Count > 0)
                {
                    _获取文本框值(c, dt_r, _ColumnName);
                }
                else
                {

                    if (c.Name == _ColumnName)
                    {
                        string c_TypeName = c.GetType().Name;
                        if (c_TypeName.StartsWith("TextBox") || c_TypeName.StartsWith("Label"))//前包含
                        {
                            if (c.Text + "" != "")
                            {
                                dt_r[_ColumnName] = c.Text;
                                break;
                            }
                        }
                        else if (c_TypeName.StartsWith("ComboBox"))
                        {
                            //if ((c as ComboBox).DataSource != null)
                            //{
                            //    dt_r[_ColumnName] = (c as ComboBox).SelectedValue;
                            //    break;
                            //}
                            //else
                            {
                                //dt_r[_ColumnName] = (c as ComboBox).SelectedItem;
                                dt_r[_ColumnName] = (c as ComboBox).Text;
                                break;
                            }

                        }
                        else if (c_TypeName.StartsWith("CheckBoxX"))
                        {
                            dt_r[_ColumnName] = (c as CheckBoxX).Checked ? 1 : 0;
                            break;
                        }
                        else if (c_TypeName.StartsWith("CheckBox"))
                        {
                            dt_r[_ColumnName] = (c as CheckBox).Checked ? 1 : 0;
                            break;
                        }
                        else if (c_TypeName.StartsWith("SwitchButton"))
                        {
                            dt_r[_ColumnName] = (c as SwitchButton).Value ? 1 : 0;
                            break;
                        }
                        else if (c_TypeName.StartsWith("DateTimePicker"))
                        {
                            dt_r[_ColumnName] = (c as DateTimePicker).Value;
                            break;

                        }
                        else if (c_TypeName.StartsWith("DateTimeInput"))
                        {
                            dt_r[_ColumnName] = (c as DevComponents.Editors.DateTimeAdv.DateTimeInput).Value;
                            break;
                        }
                        else if (c_TypeName.StartsWith("IntegerInput"))
                        {
                            dt_r[_ColumnName] = (c as DevComponents.Editors.IntegerInput).Value;
                            break;
                        }
                        else if (c_TypeName.StartsWith("DoubleInput"))
                        {
                            dt_r[_ColumnName] = (c as DevComponents.Editors.DoubleInput).Value;
                            break;
                        }
                        else
                        {
                            MessageBox.Show(_ColumnName + "赋值失败！当前封装的方法函数不支持：" + c_TypeName + " 控件！");
                        }
                    }

                }

            }
        }
        #endregion
        #region _获取update语句
        public string _获取update语句(DataTable dt_ii, string _表名, string _条件)
        {
            string _str = "";
            string sql = "";
            foreach (DataColumn item in dt_ii.Columns)
            {
                if (dt_ii.Rows[0][item.ColumnName] == DBNull.Value || dt_ii.Rows[0][item.ColumnName] == null)
                {
                    continue;
                }
                if (item.DataType.Name.ToString() == "String")
                {
                    _str += item.ColumnName + "='" + dt_ii.Rows[0][item.ColumnName] + "',";
                }
                else if (item.DataType.Name.ToString() == "DateTime")
                {
                    _str += item.ColumnName + "='" + dt_ii.Rows[0][item.ColumnName] + "',";
                    //_str += item.ColumnName + "=to_date('" + dt_ii.Rows[0][item.ColumnName] + "','YYYY-MM-DD HH24:MI:SS'),";
                }
                else if (item.DataType.Name.ToString() == "Decimal")
                {
                    _str += item.ColumnName + "=" + dt_ii.Rows[0][item.ColumnName] + ",";
                }

            }
            if (_str != "")
            {
                _str = _str.Remove(_str.Length - 1);
                sql = " update " + _表名 + " set " + _str + _条件;
            }
            return sql;

        }
        #endregion
        #region _根据表结构生成SQL插入语句
        /// <summary>
        /// 根据表结构生成SQL插入语句
        /// </summary>
        /// <param name="dt_u">数据源</param>
        /// <param name="_table_name">要插入的表名</param>
        /// <returns></returns>
        public string _生成SQL插入语句(DataTable dt_u, string _table_name)
        {
            string _cl_str = "";
            string _str = "";
            string sql = "";
            foreach (DataColumn item in dt_u.Columns)
            {
                if (dt_u.Rows[0][item.ColumnName] == DBNull.Value || dt_u.Rows[0][item.ColumnName] == null)
                {
                    continue;
                }

                if (item.DataType.Name.ToString() == "String")
                {
                    string u = dt_u.Rows[0][item.ColumnName].ToString();
                    _str += "'" + dt_u.Rows[0][item.ColumnName] + "',";
                }
                else if (item.DataType.Name.ToString() == "DateTime")//TNND,这个是个坑，不能把时间放到SQL最后一位，有逗号；
                {
                    string u = dt_u.Rows[0][item.ColumnName].ToString();
                    //if (u.ToUpper() == "SYSDATE")
                    //{
                    //    _str += "SYSDATE,";
                    //}
                    //else
                    {
                        _str += "'" + dt_u.Rows[0][item.ColumnName] + "',";
                    }
                }
                else if (item.DataType.Name.ToString() == "Decimal")
                {
                    string u = dt_u.Rows[0][item.ColumnName].ToString();
                    _str += "" + dt_u.Rows[0][item.ColumnName] + ",";
                }
                else
                {
                    continue;
                }
                _cl_str += item.ColumnName + ",";

            }
            if (_cl_str != "" && _str != "")
            {
                _cl_str = _cl_str.Remove(_cl_str.Length - 1);
                _str = _str.Remove(_str.Length - 1);
                sql = " INSERT INTO " + _table_name + " (" + _cl_str + ") VALUES (" + _str + ")";
            }

            return sql;
        }
        #endregion
        //清空文本框内容
        public void _清除区域控件内容(Control ctrl1)
        {
            foreach (Control ctrl in ctrl1.Controls)
            {
                if (ctrl is TextBox)
                    ctrl.Text = "";
                if (ctrl is DateTimePicker)
                    ctrl.Text = "";
            }
        }
        private void _填充从表信息(string _id, bool _ReadOnly)
        {
            try
            {
                string sql = "select * " +
           " from input_data_item A " +
              " where A.BILL_NO = '" + _id + "'";
                DataTable dt_ii = db1.SelectDataBase(sql);
                //dataGridViewX2.DataSource = null;
                dataGridViewX2.Rows.Clear();
                if (dt_ii.Rows.Count > 0)
                {
                    dataGridViewX2.Rows.Add(dt_ii.Rows.Count);
                    for (int i = 0; i < dt_ii.Rows.Count; i++)
                    {
                        foreach (DataGridViewColumn item in dataGridViewX2.Columns)
                        {
                            if (dt_ii.Columns.Contains(item.Name))
                            {
                                dataGridViewX2[item.Name, i].Value = dt_ii.Rows[i][item.Name];
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBoxEx.Show(ex.ToString());
            }
            
        }

        private void buttonX_update_Click(object sender, EventArgs e)
        {
            //if (permission.ModFlag != true)
            //{
            //    MessageBox.Show("你没修改权限！");
            //    return;
            //}
            //string sql_ii = "select * from SP_IQC where BILL_NO='" + CHECK_BILL_NO.Text + "' and STATUS=1";
            //if (db.CheckSQL(sql_ii))
            //{
            //    MessageBox.Show("该单据已经过来料检验审核，无法修改！");
            //    return;
            //}
            if (!string.IsNullOrEmpty(BILL_NO.Text))
            {
                string sql_ii2 = "SELECT STATUS FROM input_data WHERE BILL_NO='" + BILL_NO.Text + "'";
                if (db1.GetColumnObject(sql_ii2).ToString() == "1")
                {

                    MessageBox.Show("单据：" + BILL_NO.Text + "已经审核！不能修改");
                    return;
                }
            }
            _填充信息(BILL_NO.Text, true);
            _填充从表信息(BILL_NO.Text, false);
            label_status.Text = "修改";
        }

        private void buttonX_delete_Click(object sender, EventArgs e)
        {
            //if (permission.DelFlag != true)
            //{
            //    MessageBox.Show("你没删除权限！");
            //    return;
            //}
            //string sql = "select * from SP_IQC where BILL_NO='" + CHECK_BILL_NO.Text + "' and STATUS=1";


            if (BILL_NO.Text.Trim() == "")
            {
                return;
            }
            string sql_ii2 = "SELECT STATUS FROM input_data WHERE BILL_NO='" + BILL_NO.Text + "'";
            if (db1.GetColumnObject(sql_ii2).ToString() == "1")
            {
                MessageBox.Show("单据：" + BILL_NO.Text + "已经审核！不能删除");
                return;
            }
            DialogResult dr = MessageBox.Show(this, "确认要删除吗？", "提示", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
            if (dr != DialogResult.Yes)
            {
                return;
            }

            string sql_ii1 = "DELETE FROM input_data WHERE BILL_NO='" + BILL_NO.Text + "' ";
            int s = db1.ExcuteSQL(sql_ii1);

            sql_ii2 = "DELETE from input_data_item where BILL_NO='" + BILL_NO.Text + "' ";
            int s2 = db1.ExcuteSQL(sql_ii2);

            if (s >= 1 && s2 >= 1)
            {
                MessageBox.Show("删除成功");
            }
            else
            {
                MessageBox.Show("删除失败");
            }
            _填充信息(BILL_NO.Text, false);
            _填充从表信息(BILL_NO.Text, false);
        }
        #region 保存
        

            
        private void buttonX_save_Click(object sender, EventArgs e)
        {
            if (BILL_NO.Text.Trim() == "")
            {
                MessageBox.Show("单据编号不能为空");
                return;
            }
            if (OPERATOR.Text.Trim() == "")
            {
                 MessageBox.Show("操作员工不能为空");
                return;
            }
            if (_导入数据==false)
            {
                 MessageBox.Show("请先导入数据！");
                return;
            }

          
            if (label_status.Text == "修改")
            {
                DialogResult dr = MessageBox.Show(this, "该操作会导致数据发生变化，是否继续？",
                    "提示", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
                if (dr != DialogResult.Yes)
                {
                    return;
                }
            }
            if (dataGridViewX2.RowCount == 0)
            {
                 MessageBox.Show(" 单据明细为空，无法保存！");
                return;
            }
            string sql单头 = "", sql单身 = "";
            sql单头 = "select * from input_data where 1=2 ";
            DataTable dt_PO = db1.SelectDataBase(sql单头);
            sql单身 = "select * from input_data_item where 1=2 ";
            DataTable dt_PO_ITEM = db1.SelectDataBase(sql单身);

            int _单头条数 = 0; //_单身条数 = 0;
            //OracleConnection Conn = new OracleConnection();
            //OracleCommand cmd2 = new OracleCommand();
            //Conn = new OracleConnection(Check_Barcode.DAO.OracleConnManager.M_ConnStr);
            //Conn.Open();
            //cmd2 = Conn.CreateCommand();
            //OracleTransaction tran2 = Conn.BeginTransaction();
            //cmd2.Transaction = tran2;

            try
            {
                DataRow dr = dt_PO.NewRow();
                foreach (DataColumn item in dt_PO.Columns)
                {
                    _获取文本框值(groupPanel3, dr, item.ColumnName);
                }

                dt_PO.Rows.Add(dr);

                if (label_status.Text == "新增")
                {
                    sql单头 = "select now() as idatetime;";
                    //OleDbConnection this_conn=new OleDbConnection(dbstr);
                    //this_conn.Open();
                    //OleDbCommand cmd = this_conn.CreateCommand();
                    //cmd.CommandText = sql单头;
                    //OleDbDataReader reader2 = cmd.ExecuteReader();
                    OleDbConnection con = new OleDbConnection(dbstr);
                    con.Open();
                    OleDbCommand cmd = con.CreateCommand();
                    cmd.CommandText = sql单头;
                    OleDbDataReader reader2 = cmd.ExecuteReader();
                    
                    //MySql.Data.MySqlClient.MySqlDataReader reader1 = db1.ExecuteReader(sql单头);
                    reader2.Read();
                    dt_PO.Rows[0]["ID"] = Guid.NewGuid().ToString();
                    dt_PO.Rows[0]["CREATE_DATE"] = reader2["idatetime"];
                    dt_PO.Rows[0]["CREATE_BY"] = CREATE_BY.Text;
                    dt_PO.Rows[0]["QTY"] = QTY.Text;                    
                    dt_PO.Rows[0]["STATUS"] = 0;
                    dt_PO.Rows[0]["BILL_NO"] = BILL_NO.Text.ToString();
                    sql单头 = _生成SQL插入语句(dt_PO, "input_data");
                }
                else if (label_status.Text == "修改")
                {
                    //sql = "SELECT UPDATE_DATE FROM SP_INSTOCK";
                    //cmd2.CommandText = sql;
                    //OracleDataReader reader1 = cmd2.ExecuteReader();
                    //reader1.Read();
                    dt_PO.Rows[0]["UPDATE_DATE"] = DateTime.Now;
                    dt_PO.Rows[0]["UPDATE_BY"] = "admin";
                    sql单头 = _获取update语句(dt_PO, "input_data", "WHERE BILL_NO='" + dr["BILL_NO"] + "'");
                }
                else
                {
                    MessageBox.Show("异常：");
                    return;
                }
                //明细
                if (label_status.Text == "修改")
                {
                    sql单身 = "DELETE FROM input_data_item WHERE BILL_NO='" + dr["BILL_NO"] + "'";
                    db1.ExcuteSQL(sql单身);
                }
                //for (int i = 0; i < dataGridViewX2.RowCount; i++)
                //{
                //    dt_PO_ITEM.Rows.Clear();
                //    DataRow dr2 = dt_PO_ITEM.NewRow();
                //    foreach (DataGridViewColumn item in dataGridViewX2.Columns)
                //    {
                //        if (dt_PO_ITEM.Columns.Contains(item.Name))
                //        {
                //            if (dataGridViewX2[item.Name, i].Value + "" != "")
                //            {
                //                dr2[item.Name] = dataGridViewX2[item.Name, i].Value;
                //            }
                //            else
                //            {
                //                dr2[item.Name] = DBNull.Value;
                //            }
                //        }
                //    }

                //    dr2["ID"] = Guid.NewGuid().ToString();
                //    dr2["BILL_NO"] = BILL_NO.Text;
                //    dt_PO_ITEM.Rows.Add(dr2);
                //    sql单身 = _生成SQL插入语句(dt_PO_ITEM, "input_data_item");
                //    _单身条数 += db1.ExcuteSQL(sql单身);//单身
                //}

                if (label_status.Text == "新增")
                {
                    sql单头 = _生成SQL插入语句(dt_PO, "input_data");
                    _单头条数 += db1.ExcuteSQL(sql单头);//单头
                }
                if (label_status.Text == "修改")
                {
                    sql单头 = _获取update语句(dt_PO, "input_data", "WHERE BILL_NO='" + dr["BILL_NO"] + "'");
                    _单头条数 += db1.ExcuteSQL(sql单头);//单头
                }
                 MessageBox.Show(" 共保存入了" + _单头条数 + "条单头数据");
                _NO = dr["BILL_NO"] + "";
                _填充信息(_NO, false);
                _填充从表信息(_NO, true);
                label_status.Text = "详览";

                //_清除区域控件内容(groupPanel4);    //清空文本框内容
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
                return;
            }
            finally
            {

            }
        }
        #endregion

        #region 取消
        private void buttonX_Cancel_Click(object sender, EventArgs e)
        {
            _填充信息(_NO, false);
            _填充从表信息(_NO, true);
            label_status.Text = "详览";
        }
        #endregion

        private void dataGridViewX3_RowPostPaint(object sender, DataGridViewRowPostPaintEventArgs e)
        {
            //dataGridView添加行号
            try
            {
                Rectangle rectangle = new Rectangle(e.RowBounds.Location.X,
                    Convert.ToInt32(e.RowBounds.Location.Y + (e.RowBounds.Height - dataGridViewX3.RowHeadersDefaultCellStyle.Font.Size) / 2),
                    dataGridViewX3.RowHeadersWidth - 4, e.RowBounds.Height);
                TextRenderer.DrawText(e.Graphics, (e.RowIndex + 1).ToString(),
                    dataGridViewX3.RowHeadersDefaultCellStyle.Font, rectangle, dataGridViewX3.RowHeadersDefaultCellStyle.ForeColor,
                    TextFormatFlags.Right);
            }
            catch (Exception ex)
            {
                Console.Write("dgv1_RowPostPaint：" + ex.Message);
            }
        }

        #region 删除行
        private void buttonX_Row_Delete_Click(object sender, EventArgs e)
        {
            if (dataGridViewX2.CurrentRow != null)
            {
                int j = 0;
                for (int i = dataGridViewX2.SelectedRows.Count - 1; i >= 0; i--)
                {
                    dataGridViewX2.Rows.Remove(dataGridViewX2.SelectedRows[i]);
                    j++;
                }
                if (j == 0)
                {
                    dataGridViewX2.Rows.Remove(dataGridViewX2.CurrentRow);
                }

            }
        }
        #endregion

        private void dataGridViewX2_RowPostPaint(object sender, DataGridViewRowPostPaintEventArgs e)
        {
            //dataGridView添加行号
            try
            {
                Rectangle rectangle = new Rectangle(e.RowBounds.Location.X,
                    Convert.ToInt32(e.RowBounds.Location.Y + (e.RowBounds.Height - dataGridViewX2.RowHeadersDefaultCellStyle.Font.Size) / 2),
                     dataGridViewX2.RowHeadersWidth - 4, e.RowBounds.Height);
                TextRenderer.DrawText(e.Graphics, (e.RowIndex + 1).ToString(),
                     dataGridViewX2.RowHeadersDefaultCellStyle.Font, rectangle, dataGridViewX2.RowHeadersDefaultCellStyle.ForeColor,
                    TextFormatFlags.Right);
            }
            catch (Exception ex)
            {
                Console.Write("dgv1_RowPostPaint：" + ex.Message);
            }
        }

        private void buttonX_query_Click(object sender, EventArgs e)
        {
            string sql_ii = "select A.* FROM input_data A" +
            " WHERE  1=1 ";
            if (textBoxX1.Text.Trim() + "" != "")
            {
                sql_ii += " and A.BILL_NO='" + textBoxX1.Text.Trim() + "' ";
            }
            if (dateX_CREATE_DATE.LockUpdateChecked == true)
            {
                sql_ii += " and A.CREATE_DATE >='" + dateX_CREATE_DATE.Value + "' ";
            }
            if (dateX_CREATE_DATE2.LockUpdateChecked == true)
            {
                sql_ii += " and A.CREATE_DATE<='" + dateX_CREATE_DATE2.Value + "' ";
            }
            if (radioButton_Y.Checked == true)
            {
                sql_ii += " and A.STATUS='1' ";
            }
            if (radioButton_N.Checked == true)
            {
                sql_ii += "and A.STATUS='0' ";
            }
            if ((comboBoxEx2.SelectedItem + "").Trim() != "" && (comboBoxEx3.SelectedItem + "").Trim() != "" && textBoxX2.Text.Trim() != "")
            {
                string str2 = _ziduan(comboBoxEx2.SelectedItem.ToString(), dataGridViewX1.Columns);
                if (str2.Trim() != "")
                {
                    sql_ii += " AND " + str2 + " " + _Tiaojian(comboBoxEx3.SelectedItem.ToString(), textBoxX2.Text.ToString());
                }
            }
            if (!string.IsNullOrEmpty(textBoxX3.Text.Trim()))
            {
                string str = textBoxX3.Text;
                foreach (DataGridViewColumn item in dataGridViewX1.Columns)
                {
                    if (str.Contains("[" + item.HeaderText + "]"))
                    {
                        str = str.Replace("[" + item.HeaderText + "]", item.Name);
                    }
                }
                // string str= string str2 = _Class1_wzh.ziduan(comboBoxEx2.SelectedItem.ToString(), dataGridViewX1.Columns);
                sql_ii += " " + str + "";
            }
            sql_ii += " ORDER BY A.CREATE_DATE DESC";//创建时间倒序，最新的单据在最上面
            dataGridViewX1.DataSource = db1.SelectDataBase(sql_ii);
        }

        private void dataGridViewX1_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            int dataGridView_row = 100;
            if (dataGridViewX1.CurrentRow == null)
            {
                return;
            }
            if (dataGridView_row != dataGridViewX1.CurrentRow.Index)
            {
                dataGridView_row = dataGridViewX1.CurrentRow.Index;
                string sql = "select * " +
                " from input_data_item A " +
                " where A.BILL_NO = '" + dataGridViewX1.CurrentRow.Cells["BILL_NO"].Value.ToString() + "'";
                DataTable dt_ii = db1.SelectDataBase(sql);

                dataGridViewX3.DataSource = dt_ii;
                dataGridView_row = dataGridViewX1.CurrentRow.Index;
            }
        }

        private void dataGridViewX1_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
        {
            if (buttonX_save.Enabled == true)
            {
               MessageBoxEx.Show("发现有单据正在第二页签里编辑中，请先保存或取消当前正在编辑的单据！");
                return;
            }
            if (dataGridViewX1.CurrentRow != null)
            {
                _NO = dataGridViewX1.CurrentRow.Cells["BILL_NO"].Value != null ? dataGridViewX1.CurrentRow.Cells["BILL_NO"].Value.ToString() : "";
                superTabControl1.SelectedTabIndex = 1;

                _填充信息(_NO, false);
                _填充从表信息(_NO, true);

                string sql = "select * from input_data where BILL_NO='" + BILL_NO.Text + "' and STATUS='1' ";
                if (db1.CheckSQL(sql))
                {
                    this.pictureBox3.Visible = true;
                }
                else
                {
                    this.pictureBox3.Visible = false;
                }
            }
        }

        private void dataGridViewX1_RowPostPaint(object sender, DataGridViewRowPostPaintEventArgs e)
        {
            //dataGridView添加行号
            try
            {
                Rectangle rectangle = new Rectangle(e.RowBounds.Location.X,
                    Convert.ToInt32(e.RowBounds.Location.Y + (e.RowBounds.Height - dataGridViewX1.RowHeadersDefaultCellStyle.Font.Size) / 2),
                    dataGridViewX1.RowHeadersWidth - 4, e.RowBounds.Height);
                TextRenderer.DrawText(e.Graphics, (e.RowIndex + 1).ToString(),
                    dataGridViewX1.RowHeadersDefaultCellStyle.Font, rectangle, dataGridViewX1.RowHeadersDefaultCellStyle.ForeColor,
                    TextFormatFlags.Right);
            }
            catch (Exception ex)
            {
                Console.Write("dgv1_RowPostPaint：" + ex.Message);
            }
        }

        private void buttonX_audits_Click(object sender, EventArgs e)
        {
            if (BILL_NO.Text == "")
            {
                MessageBoxEx.Show("单据编号不能为空");
                return;
            }
            //if (!permission.ApprovalFlag)
            //{
            //    MessageBox.Show("没有审核权限");
            //    return;
            //}
            //string sql1 = "select * from SP_IQC  WHERE BILL_NO='" + CHECK_BILL_NO.Text + "' AND STATUS=0 ";
            //db db1 = new db();
            //if (db1.CheckSQL(sql1))
            //{
            //    MessageBox.Show("该单据尚未检验，不能审核！");
            //    return;
            //}
            if (!string.IsNullOrEmpty(BILL_NO.Text))
            {
                string sql_ii2 = "SELECT STATUS FROM input_data WHERE BILL_NO='" + BILL_NO.Text + "'";
                if (db1.GetColumnObject(sql_ii2).ToString() != "0")
                {
                    MessageBoxEx.Show("单据：" + BILL_NO.Text + "已审核！不能重复审核");
                    return;
                }
            }
            if (MessageBox.Show(this, "确定要审核？", "提示", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.No)
            {
                return;
            }
            int result = 0;


            string sql_ii = "UPDATE input_data SET STATUS='1',AUDIT_BY='admin',AUDIT_DATE='" + DateTime.Now + "'" +
                " where BILL_NO='" + BILL_NO.Text + "' ";

            result += db1.ExcuteSQL(sql_ii);
           MessageBoxEx.Show("审核成功！共审核了" + result + "笔单据.");
            this.pictureBox3.Visible = true;
            _填充信息(BILL_NO.Text, false);
            _填充从表信息(BILL_NO.Text, true);
        }

        private void dataGridViewX3_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            int dataGridView_row = 100;
            if (dataGridViewX3.CurrentRow == null)
            {
                return;
            }
            if (dataGridView_row != dataGridViewX3.CurrentRow.Index)
            {
                dataGridView_row = dataGridViewX3.CurrentRow.Index;
                string sql = "select * " +
                " from data A " +
                " where A.mac2 = '" + dataGridViewX3.CurrentRow.Cells["SN"].Value.ToString() + "'";
                DataTable dt_ii = db1.SelectDataBase(sql);

                dataGridViewX4.DataSource = dt_ii;
                dataGridView_row = dataGridViewX3.CurrentRow.Index;
            }
        }

        private void dataGridViewX3_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
        {
            superTabControl2.SelectedTabIndex = 1;
            int dataGridView_row = 100;
            if (dataGridViewX3.CurrentRow == null)
            {
                return;
            }
            if (dataGridView_row != dataGridViewX3.CurrentRow.Index)
            {
                dataGridView_row = dataGridViewX3.CurrentRow.Index;
                string sql = "select * " +
                " from data A " +
                " where A.mac2 = '" + dataGridViewX3.CurrentRow.Cells["SN"].Value.ToString() + "'";
                DataTable dt_ii = db1.SelectDataBase(sql);

                dataGridViewX4.DataSource = dt_ii;
                dataGridView_row = dataGridViewX3.CurrentRow.Index;
            }
        }

        private void dataGridViewX4_RowPostPaint(object sender, DataGridViewRowPostPaintEventArgs e)
        {
            //dataGridView添加行号
            try
            {
                Rectangle rectangle = new Rectangle(e.RowBounds.Location.X,
                    Convert.ToInt32(e.RowBounds.Location.Y + (e.RowBounds.Height - dataGridViewX4.RowHeadersDefaultCellStyle.Font.Size) / 2),
                    dataGridViewX4.RowHeadersWidth - 4, e.RowBounds.Height);
                TextRenderer.DrawText(e.Graphics, (e.RowIndex + 1).ToString(),
                    dataGridViewX4.RowHeadersDefaultCellStyle.Font, rectangle, dataGridViewX4.RowHeadersDefaultCellStyle.ForeColor,
                    TextFormatFlags.Right);
            }
            catch (Exception ex)
            {
                Console.Write("dgv1_RowPostPaint：" + ex.Message);
            }
        }

        private void buttonX1_Click(object sender, EventArgs e)
        {

        }












    }
}
